package com.lw.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author LW
 * @2020/8/21 14:26
 */

/**
 * 异步调用：CompletableFuture
 * //异步执行
 * //成功回调
 * //失败回调
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //异步任务：发起的时候，并不会占用程序的时间
        //runAsync()运行异步
        CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(()->{

            System.out.println(Thread.currentThread().getName()+"runAsync==>Void");
        });
        System.out.println("1111");
        completableFuture1.get();//获取执行结果

        /**supplyAsync
         * 成功与失败（null）有返回值
         */
        CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"supplyAsync==>String");
            int i = 10/0;
            return "成功了";
        });
        System.out.println(completableFuture2.whenComplete((t, u) -> {
            System.out.println("t-->" + t);//正常的返回结果
            System.out.println("u-->" + u);//错误信息
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return "失败了";
        }).get());
    }
}
